window.addEventListener('load', () => {
    //els 的属性是结构中用到的元素
    let els = {
        content: document.querySelector('.content'),
        startBtn: document.querySelectorAll('button')[0],
        reloadBtn: document.querySelectorAll('button')[1]
    };
    //标记地区有没有被使用0为未标记，1为已标记
    let flag = [];
    let jieliu = false;
    for (let i = 0; i < 900; i++) {
        flag[i] = 0;
    };
    let lock = true;
    //设置位置
    let arr = [];           //存放蛇头和蛇身的实例
    let head = null;         //定义蛇头
    let foodPosition = [];           //定义食物的位置
    let food = null;        //定义食物元素
    //定义两个数组，now 和next 

    els.startBtn.addEventListener('click', (e) => {
        e.target.style.display = 'none';
        load();
    })
    //加载游戏
    function load() {
        //创建蛇头
        head = new createHead();
        arr.push(head);
        createFood();
    }
    //创建身体
    class createBody {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            flag[this.x * 30 + this.y] = 1;
            this.el = document.createElement('div');
            this.el.style.left = x * 20 + 'px';
            this.el.style.top = y * 20 + 'px';
            this.el.classList.add('body');
            els.content.appendChild(this.el);
        }
    }
    //创建食物
    function createFood() {
        let x = Math.floor(Math.random() * 30);
        let y = Math.floor(Math.random() * 30);
        while (flag[x * 30 + y]) {
            x = Math.floor(Math.random() * 30);
            y = Math.floor(Math.random() * 30);
        };
        foodPosition[0] = x;
        foodPosition[1] = y;
        food = document.createElement('div');
        food.classList.add('food');
        food.style.left = x * 20 + 'px';
        food.style.top = y * 20 + 'px';
        els.content.appendChild(food);
    }
    //蛇头移动
    function headMove() {
        if (this.director === 'right') {
            this.x = this.x + 1;
            this.el.style.transform = 'rotate(0deg)';
        } else if (this.director === 'up') {
            this.y = this.y - 1;
            this.el.style.transform = 'rotate(270deg)';
        } else if (this.director === 'left') {
            this.x = this.x - 1;
            this.el.style.transform = 'rotate(180deg)';
        } else if (this.director === 'down') {
            this.y = this.y + 1;
            this.el.style.transform = 'rotate(90deg)';
        };
        if (this.x === 30 || this.y === 30 || this.x < 0 || this.y < 0 || flag[this.x * 30 + this.y]) {
            clearInterval(this.interval);
            els.reloadBtn.style.display = 'block';
            return true;
        }
        this.el.style.left = this.x * 20 + 'px';
        this.el.style.top = this.y * 20 + 'px';
    }
    //创建蛇头和前两个身子节点
    class createHead {
        constructor() {
            this.el = document.createElement('div');
            this.el.classList.add('head');
            els.content.appendChild(this.el);
            this.interval = null;
            this.director = 'right';
            this.x = 0;
            this.y = 0;
            flag[this.x * 30 + this.y] = 1;
            this.run();
        };
        run() {
            //判断蛇头下一次的位置和方向
            let num = 2;
            this.interval = setInterval(() => {
                //先让所有的身体节点移动到前一个节点的位置，然后再移动头部
                let last = [arr[arr.length - 1].x, arr[arr.length - 1].y];      //记录当前最后一个节点的位置
                let first = [arr[0].x, arr[0].y];                               //记录当前蛇头的位置
                flag[last[0] * 30 + last[1]] = 0;
                let aaaa = headMove.call(this);
                if (aaaa) {
                    return;
                }
                for (let i = arr.length - 1; i > 0; i--) {
                    if (i === 1) {
                        arr[i].x = first[0];
                        arr[i].y = first[1];

                    } else {
                        arr[i].x = arr[i - 1].x;
                        arr[i].y = arr[i - 1].y;
                    }
                    flag[arr[i].x * 30 + arr[i].y] = 1;
                    arr[i].el.style.left = arr[i].x * 20 + 'px';
                    arr[i].el.style.top = arr[i].y * 20 + 'px';
                }
                if (num > 0) {
                    num--;
                    arr.push(new createBody(0, 0));
                }
                //当移动之后的位置是食物时，吃掉，然后创建新的食物，蛇身变长
                if (this.x === foodPosition[0] && this.y === foodPosition[1]) {
                    els.content.removeChild(food);
                    createFood();
                    arr.push(new createBody(...last));
                }
                //当上面的判断条件全部判断完之后改变蛇头当前位置的标记
                flag[this.x * 30 + this.y] = 1;
                jieliu = true
            }, 200);
        }
    }
    //重新开始
    els.reloadBtn.addEventListener('click', (e) => {
        //先清除实例，释放内存
        for (let i = 0; i < arr.length; i++) {
            els.content.removeChild(arr[i].el);
            arr[i] = null;
        };
        arr = [];
        head = null;
        for (let i = 0; i < 900; i++) {
            flag[i] = 0;
        }
        els.content.removeChild(document.querySelector('.food'));
        els.startBtn.style.display = 'block';
        els.reloadBtn.style.display = 'none';
    });

    //键盘按下改变方向
    document.onkeydown = function (e) {
        if (jieliu) {
            jieliu = false;
            if (e.key == 'ArrowLeft' && head.director != 'right') {
                head.director = 'left';
            } else if (e.key == 'ArrowRight' && head.director != 'left') {
                head.director = 'right';
            } else if (e.key == 'ArrowUp' && head.director != 'down') {
                head.director = 'up';
            } else if (e.key == 'ArrowDown' && head.director != 'up') {
                head.director = 'down';
            }
        }
    }
});